package com.wangs.exception;

import com.wangs.data.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ErrorAdvice {
    @ExceptionHandler
    public Object handler(Exception e) {
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        Map<String, String> errors = new HashMap<>();

        // 获取绑定结果
        BindingResult bindingResult = e.getBindingResult();

        // 遍历所有错误信息
        bindingResult.getAllErrors().forEach((error) -> {
            // 获取字段名
            String fieldName = ((FieldError) error).getField();
            // 获取@NotNull等注解中的message信息
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return Result.fail("参数校验错误", errors);
    }
}